/*
 * Bitmap.cpp
 *
 *  Created on: Oct 5, 2012
 *      Author: burek
 */

#include "Bitmap.h"
#include <cstdlib>
#include <cstring>
#include <cstdio>

//#define _DEBUG

Bitmap::Bitmap(Uint32 Width, Uint32 Height)
{
	width = Width;
	height = Height;
	data = (Uint32*)malloc(width * height * 4);
}

Bitmap::~Bitmap()
{
	free(data);
}

void Bitmap::pset(Uint32 x, Uint32 y, Uint32 pixel)
{
#ifdef _DEBUG
	if(x >= 0 && y >= 0 && x < width && y < height) {
#endif
		data[x + y * width] = pixel;
#ifdef _DEBUG
	}
#endif
}

void Bitmap::pset(Uint32 x, Uint32 y, Uint8 R, Uint8 G, Uint8 B, Uint8 A)
{
#ifdef _DEBUG
	if(x >= 0 && y >= 0 && x < width && y < height) {
#endif
		data[x + y * width] = FROM_RGBA(R, G, B, A);
#ifdef _DEBUG
	}
#endif
}

Uint32 Bitmap::pget(Uint32 x, Uint32 y) const
{
#ifdef _DEBUG
	if(x >= 0 && y >= 0 && x < width && y < height) {
#endif
		return data[x + y * width];
#ifdef _DEBUG
	}
	else
	{
		return 0;
	}
#endif
}

void Bitmap::clear()
{
	memset(data, 0, width * height * 4);
}

bool Bitmap::saveToBMP(const char *fileName) const
{
	FILE *f = fopen(fileName, "wb");
	if(f == NULL)
		return false;

	byte hdr[] = {'B','M','6','0','*',0,0,0,0,0,'6',0,0,0,'(',0,0,0,0,5,0,0,0xD0,2,0,0,1,0,32,0,0,0,0,0,0,'0','*',0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
	hdr[0x12 + 0] = width & 255;
	hdr[0x12 + 1] = (width >> 8) & 255;
	hdr[0x12 + 2] = (width >> 16) & 255;
	hdr[0x12 + 3] = (width >> 24) & 255;

	hdr[0x16 + 0] = height & 255;
	hdr[0x16 + 1] = (height >> 8) & 255;
	hdr[0x16 + 2] = (height >> 16) & 255;
	hdr[0x16 + 3] = (height >> 24) & 255;

	fwrite(hdr, 1, 54, f);
	for(int y = height - 1; y >= 0; y--)
		fwrite(data + y * width, width * 4, 1, f);

	fclose(f);
	return true;
}

void Bitmap::bltTo(Bitmap *target, Uint32 sx, Uint32 sy, Uint32 dx, Uint32 dy, Uint32 w, Uint32 h)
{
	if(target == this) return;
	Uint32 *src = &(data[sx + sy * width]);
	Uint32 *dst = &(target->data[dx + dy * target->width]);
	Uint32 srcStride = width;
	Uint32 dstStride = target->width;

	for(Uint32 i = 0; i < h; ++i)
	{
		memcpy(dst, src, w * sizeof(Uint32));
		src += srcStride;
		dst += dstStride;
	}
}

